<template>
  <div class="prescription-container">
    <div class="clearAndMargin">
      <el-button
        type="primary"
        style="float: right"
        @click="selClick"
        :disabled="disabled"
      >
        选择模板
      </el-button>
    </div>
    <m-table v-model="list" ref="mtRef" :disabled="disabled"></m-table>
    <medicinal-select
      :disabled="disabled"
      @selectData="selData"
    ></medicinal-select>
    <prescription-template
      ref="ptRef"
      @success="imgToSave"
    ></prescription-template>
    <div class="footer-div">
      <debounce-btn
        class="footer-button"
        type="primary"
        @debounce="getPrescriptionImg(2)"
        :disabled="disabled"
      >
        提交
      </debounce-btn>
      <debounce-btn
        class="footer-button"
        type="primary"
        @debounce="toSave(1)"
        :disabled="disabled"
      >
        保存
      </debounce-btn>
      <el-button
        class="footer-button"
        :disabled="disabled"
        @click="toSave(1, null, true)"
      >
        存为模板
      </el-button>
      <el-button
        class="footer-button"
        :disabled="disabled"
        @click="getPrescriptionImg(3)"
      >
        延伸药房发货
      </el-button>
    </div>
    <template-dialog ref="tdRef" @selResult="templateSel"></template-dialog>
  </div>
</template>
<script>
  import MedicinalSelect from '@/components/MedicinalSelect'
  import MTable from '@/components/MedicinaModifylTable'
  import { reactive, ref, toRefs } from '@vue/reactivity'
  import {
    load,
    save,
    saveASTemplate,
    loadPrescriptionImgInfo,
  } from '@/api/modules/prescription'
  import { watch } from '@vue/runtime-core'
  import { useRoute } from 'vue-router'
  import templateDialog from './components/TemplateDialog'
  import common from '@/utils/common'
  import { useStore } from 'vuex'
  export default {
    name: 'prescription',
    components: { MedicinalSelect, MTable, templateDialog },
    props: { pid: [String, Number] },
    setup(props) {
      const selData = function (medicinal) {
        console.log('selData = ' + JSON.stringify(medicinal))
        d.list.push(medicinal)
      }
      let isVisble = ref(false)
      const d = reactive({ list: [], disabled: null })

      const ptRef = ref(null)
      const mtRef = ref(null)
      // status  1 保存 2 发送至患者. 二次保存需要id
      const imgToSave = function (config) {
        toSave(config.status, config.imgUrl)
      }

      const store = useStore()
      const toSave = async function (status, imgUrl, isSaveTemplate) {
        const checkedList = mtRef.value.getCheckData()
        if (Array.isArray(checkedList) && checkedList.length === 0) return
        const detailed = checkedList.map((item) => {
          // 适配后台 搜索id
          if (!item.drugId) item.drugId = item.id
          return item
        })
        common.XmLoading()
        await save({
          detailed,
          medicalRecordId: route.query.emrId,
          patientId: props.pid,
          status,
          imgUrl,
        })
          .then(() => {
            common.XmLoading(false)
            if (isSaveTemplate) {
              saveTemplate()
              return
            }
            common.XmMessage(0, status === 1 ? '保存成功' : '提交成功')
            toLoad(route.query.emrId)
            store.dispatch('patient/loadEmrStatus', {
              medicalRecordId: route.query.emrId,
              patientId: route.query.id,
            })
          })
          .catch(() => {
            common.XmLoading(false)
            return
          })
      }

      const getPrescriptionImg = async function (status) {
        common.XmLoading()
        loadPrescriptionImgInfo({ medicalRecordId: route.query.emrId })
          .then((res) => {
            common.XmLoading(false)
            ptRef.value.init(res.data, true, status)
          })
          .catch(() => {
            common.XmLoading(false)
          })
      }
      // 通过病历id 加载病历数据
      const toLoad = async function (id) {
        // BUG 2. 搜索给id, 保存 存为 drugID
        if (!id) return
        const res = await load({ medicalRecordId: id })
        if (res.data && res.data.status) d.disabled = res.data.status === 2
        if (res.data && res.data.detailed) d.list = res.data.detailed
      }
      const tdRef = ref(null)
      const selClick = async function () {
        tdRef.value.initData()
      }
      const templateSel = function (val) {
        // 加载选择模板时给的数据
        console.log('val =' + JSON.stringify(val))
        d.list = d.list.concat(val)
        console.log('d.list =' + JSON.stringify(d.list))
      }
      const saveTemplate = async function () {
        // 将当前数据存为模板
        common.XmLoading()
        const res = await saveASTemplate({ medicalRecordId: route.query.emrId })
          .then(() => {
            console.log('res ' + JSON.stringify(res))
            common.XmMessage(0, '保存模板成功')
          })
          .catch(() => {
            console.log('catch')
            common.XmLoading(false)
          })
      }
      const route = useRoute()
      watch(
        () => route.query.emrId,
        async (res) => {
          toLoad(res)
        },
        { immediate: true }
      )
      return {
        isVisble,
        selData,
        toSave,
        toLoad,
        ptRef,
        selClick,
        tdRef,
        mtRef,
        getPrescriptionImg,
        imgToSave,
        templateSel,
        saveTemplate,
        ...toRefs(d),
      }
    },
  }
</script>
<style lang="scss" scoped>
  .clearAndMargin {
    overflow: hidden;
    margin-bottom: 12px;
  }
  .footer-div {
    margin-top: 20px;
    .el-button {
      float: right;
      margin-right: 12px;
      margin-left: 0px;
    }
  }
</style>
